package cc.telecomdigital.tdstock.Http.Tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;

public class CommonTools
{
	static public enum BMPPage
	{
		STOCK,
		MONITOR,
		COP,
		TOP20_NET,
		TOP20_TURNOVER,
		CURRENT
		// INDEX,
		// FX,
	}
	
	static final private String	LOG_TAG				= "H_DataBase";
	static final private int	CONNECTION_TIMEOUT	= 1000 * 30;
	static final private int	SOCKET_TIMEOUT		= 1000 * 30;
	static final private int	READ_TIMEOUT		= 1000 * 30;

	static public List<String[]> GetDataListByDocument(Document iDocument, String[] tmps, String rootName, String... header)
	{
		List<String[]> arraysList = new ArrayList<String[]>();
		try
		{
			String[] hArray = new String[tmps.length];
			for (int i = hArray.length - 1; i >= 0; i--)
			{
				try
				{
					NodeList nodes = iDocument.getElementsByTagName(header[i]);
					Node node = nodes.item(0);
					
					hArray[i] = node.getFirstChild().getNodeValue();
					TDStockLog.d(LOG_TAG, "TMP=" + header[i] + "," + hArray[i]);
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}

			if (header.length > 0)
				arraysList.add(hArray);

			NodeList nodes = iDocument.getElementsByTagName(rootName);
			for (int i = 0; i < nodes.getLength(); i++)
			{
				Element bookElement = (Element) nodes.item(i);
				NodeList childNodes = bookElement.getChildNodes();

				String[] arrays = new String[tmps.length];

				for (int j = 0; j < childNodes.getLength(); j++)
				{
					if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE)
					{
						String name = childNodes.item(j).getNodeName();
						for (int k = 0; k < tmps.length; k++)
						{
							try
							{
								if (tmps[k].equals(name))
								{
									arrays[k] = childNodes.item(j).getFirstChild().getNodeValue();
									TDStockLog.d(LOG_TAG, "TMP=2>" + name + " , " + childNodes.item(j).getFirstChild().getNodeValue());
									break;
								}
							}
							catch (Exception e)
							{
								e.printStackTrace();
							}
						}
					}
				}
				arraysList.add(arrays);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return arraysList;
	}

	static public List<String[]> GetXMLContentListByUrl(String url, String[] tmps, String rootName, String... header)
	{
		List<String[]> arraysList = new ArrayList<String[]>();
		try
		{
			TDStockLog.i(LOG_TAG, url);

			InputStream inputStream;
//			inputStream = GetHttpURLConnectionToInputStream(url);
			inputStream = GetHttpClientToInputStream(url);
			if(inputStream == null) return null;
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document iDocument = builder.parse(inputStream);

			String[] hArray = new String[tmps.length];
			for (int i = hArray.length - 1; i >= 0; i--)
			{
				try
				{
					Node node = iDocument.getElementsByTagName(header[i]).item(0);
					
					hArray[i] = node.getFirstChild().getNodeValue();
					
					TDStockLog.d(LOG_TAG, "TMP=" + header[i] + "," + hArray[i]);
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}

			if (header.length > 0)
				arraysList.add(hArray);

			NodeList nodes = iDocument.getElementsByTagName(rootName);
			for (int i = 0; i < nodes.getLength(); i++)
			{
				Element bookElement = (Element) nodes.item(i);
				NodeList childNodes = bookElement.getChildNodes();

				String[] arrays = new String[tmps.length];

				for (int j = 0; j < childNodes.getLength(); j++)
				{
					if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE)
					{
						String name = childNodes.item(j).getNodeName();
						for (int k = 0; k < tmps.length; k++)
						{
							try
							{
								if (tmps[k].equals(name))
								{
									arrays[k] = childNodes.item(j).getFirstChild().getNodeValue();
									TDStockLog.d(LOG_TAG, "TMP=>" + name + " , " + childNodes.item(j).getFirstChild().getNodeValue());
									break;
								}
							}
							catch (Exception e)
							{
								e.printStackTrace();
							}
						}
					}
				}
				arraysList.add(arrays);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return arraysList;
	}

	public static InputStream GetHttpClientToInputStream(String urlString) throws ClientProtocolException, IOException
	{
		// HttpGet
		HttpGet httpMethod = new HttpGet(urlString);
		// HttpClient
		DefaultHttpClient client = new DefaultHttpClient();
		// HttpParams
		HttpParams httpParams = client.getParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
		HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT);
		
		client.setParams(httpParams);
		
		HttpResponse httpResponse = client.execute(httpMethod);
		
		TDStockLog.d(LOG_TAG, "HttpClient>>Status: "+httpResponse.getStatusLine().getStatusCode()+","+httpResponse.getStatusLine().getReasonPhrase());
		
		if(httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
			return null;
		return httpResponse.getEntity().getContent();
	}

	public static InputStream GetHttpURLConnectionToInputStream(String urlString) throws IOException
	{
		URL url = new URL(urlString);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setConnectTimeout(CONNECTION_TIMEOUT);
		connection.setReadTimeout(READ_TIMEOUT);
		connection.setRequestMethod("GET");
		connection.setRequestProperty(
						"User-Agent",
						"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2");
		connection.setDoOutput(true);
		
		TDStockLog.d(LOG_TAG, "HttpURLConnection>>Status: "+connection.getResponseCode()+","+connection.getResponseMessage());
		
		InputStream inputStream = connection.getInputStream();
		return inputStream;
	}

	static public String InputStreamToString(final InputStream stream) throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(stream), 16 * 1024);
		StringBuilder sb = new StringBuilder(16 * 1024);
		String line = null;
		while ((line = br.readLine()) != null)
		{
			sb.append(line + "\n");
		}
		br.close();
		return sb.toString();
	}
}
